<template>
    <div>
        <rui-page :defines="defines">
            <div>
                <Row>
                    <Alert>
                        产品模板基本信息
                    </Alert>
                </Row>
                <Row>
                    <Form ref="templateForm" :model="templateForm" :label-width="50" :rules="templateRules">
                        <Row>
                            <Col :xs="24" :md="12" :lg="8" :xl="6" v-if="numberReadonly">
                                <FormItem label="模板编号" prop="templateNumber" :label-width="100">
                                    <Input v-model="templateForm.templateNumber" style="width: 150px" :disabled="numberReadonly"/>
                                </FormItem>
                            </Col>
                            <Col :xs="24" :md="12" :lg="8" :xl="6">
                                <FormItem label="模板名称" prop="templateName" :label-width="100">
                                    <Input v-model="templateForm.templateName" style="width: 150px" :disabled="isReadonly"/>
                                </FormItem>
                            </Col>
                            <Col :xs="24" :md="12" :lg="8" :xl="6">
                                <FormItem label="模板类别" prop="templateCategory" :label-width="100">
                                    <Select v-model="templateForm.templateCategory" style="width:150px" :disabled="true">
                                        <Option v-for="item in templateCategoryQuery" :value="item.value" :key="item.value" :label="item.title">
                                            {{item.title}}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col :xs="24" :md="12" :lg="8" :xl="6">
                                <FormItem label="版本号" prop="versionNumber" :label-width="100">
                                    <Input v-model="templateForm.versionNumber" style="width: 150px" :disabled="true"/>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row style="text-align: center;">
                            <Button @click="save" icon="md-bookmark" type="primary" :loading="submitLoading" v-show="isShow">保存</Button>
                            <Button @click="backPage" icon="md-backspace" type="primary">返回</Button>
                        </Row>
                    </Form>
                </Row>
                <br>
                <Row>
                    <Alert>
                        产品模板原子信息
                    </Alert>
                </Row>
                <rui-table
                    :defineId="'defineProductAtom'"
                    :showIndex="false"
                    :columns="tamplateAtomColumns"
                    @loadDatas="remoteTableDatas"
                    @on-selection-change="changeSelect"
                    ref-query="tamplateAtomSearchForm"
                    ref="tamplateAtomTable"
                >
                    <template slot="toolBar">
                        <Button @click="add" type="primary" icon="md-add" v-show="isShow">新增</Button>
                        <Button type="error" size="small" icon="md-trash" v-show="isShow" @click="removeAll">删除</Button>
                        <Button @click="isMust" type="primary" icon="md-lock" v-show="isShow">必填</Button>
                        <Button @click="isNotMust" type="primary" icon="md-unlock" v-show="isShow">不必填</Button>
                        <Button type="primary" size="small" @click="moveTemplateAll('moveup')" icon="md-arrow-round-up" v-show="isShow">上移</Button>
                        <Button type="primary" size="small" @click="moveTemplateAll('movedown')" icon="md-arrow-round-down" v-show="isShow">下移</Button>
                        <Button type="primary" size="small" @click="moveTemplateAll('movetop')" icon="md-arrow-round-up" v-show="isShow">置顶</Button>
                        <Button type="primary" size="small" @click="moveTemplateAll('moveaend')" icon="md-arrow-round-down" v-show="isShow">置底</Button>
                    </template>
                </rui-table>

            </div>
            <Modal
                v-model="isShowModel"
                :title="modalTitle"
                :width="1000"
                :closable="false"
                :mask-closable="false"
            >
                <rui-query :label-width="200"
                           ref="searchForm"
                           :query="queryData"
                           :query-rows="searchFormOptions"
                           :more-rows="moreRows"
                />
                <Row>
                    <Alert show-icon>
                        已选择 <span class="select-count">{{selectAtomCount}}</span> 项
                        <a class="select-clear" @click="clearAtomSelectAll">清空</a>
                    </Alert>
                </Row>
                <rui-table
                    :defineId="'defineProductAtom'"
                    :showIndex="false"
                    :columns="atomColumns"
                    @loadDatas="queryData"
                    @on-selection-change="changeAtomSelect"
                    ref-query="searchForm"
                    ref="atomTable"
                >
                </rui-table>

                <div slot="footer">
                    <Button type="primary" @click="isShowModel = false">取消</Button>
                    <Button type="primary" :loading="submitLoading" @click="saveTemplateAtom">确定</Button>
                </div>
            </Modal>
        </rui-page>
    </div>
</template>
<script>

    import productAtomDefine from "../defines/product-atom-define";
    import circleLoading from "_c/circle-loading/circle-loading.vue";
    import validator from '_p/afs-core-business/pages/product/common/rules.js';

    import {getByTypes,getDictDataByType} from "_p/basic/api/admin/datadic";
    import {
        getProductTemplateInfo,
        saveOrUpdateTemplate
    } from "@/projects/afs-core-business/api/afs-product/product/product";

    import {
        getProductTemplateDetails,
        isMust,
        isNotMust,
        saveTemplateAtom,
        removeAll,
        moveTemplateAll,
    } from "@/projects/afs-core-business/api/afs-product/product/productTemplateAtom";

    import {
        getProductList,
        getProducttemplateAtomList
    } from "@/projects/afs-core-business/api/afs-product/product/productAtom";

    export default {
        name: "product-template",
        components: {
            circleLoading
        },
        props: {
            templateParms: {
                Object,
            }
        },
        data() {
            return {
                //全局显示信息
                isShow: true,
                submitLoading: false,
                operationLoading:false,
                //模板信息
                templateForm: {},
                templateRules: {
                    templateNumber: [ {required: true, message: "模板编号不能为空",trigger: "change"}, {validator: validator.numAndLetterValidator, trigger: "change"},],
                    templateName: [ {required: true, message: "模板名称不能为空",trigger: "change"}],
                },
                numberReadonly: false,
                templateCategoryQuery: [],
                isReadonly: false,
                //模板原子信息
                tamplateAtomColumns: [
                    'atomShowType','atomName' , 'atomControlType','atomIsDefault', 'isMust'
                ],
                selectList: [],
                selectCount: 0,
                //弹窗信息
                modalTitle: "新增模板原子",
                isShowModel: false,
                //原子信息
                atomColumns: [
                    'atomShowType','atomName' , 'atomControlType','atomIsDefault'
                ],
                searchFormOptions: [
                    {defineId: "defineProductAtom", span: 6, fields: ["atomName", "atomShowType"]},
                ],
                moreRows: [
                    {defineId: "defineProductAtom", span: 6, fields: ["atomControlType","atomIsDefault"]},
                ],
                selectAtomCount:0,
                selectAtomList : [],
            };
        },
        methods: {
            //初始化
            getProductTemplateInfoDetail(val) {
                if ("1" === val.status) {
                    this.isShow = true;
                    this.status = val.status;
                    this.templateForm.templateCategory = val.templateCategory;
                    this.templateForm.versionNumber = '1';
                } else if ("3" === val.status) {
                    this.isShow = false;
                    this.templateForm.id = val.id;
                    this.numberReadonly = true;
                    this.isReadonly = true;
                    this.getInfo();
                    this.refresh();
                } else {
                    this.isShow = true;
                    this.numberReadonly = true;
                    this.templateForm.id = val.id;
                    this.getInfo();
                    this.refresh();
                }
            },
            //加载模板信息
            getInfo() {
                getProductTemplateInfo(this.templateForm).then(res => {
                    if (res.code === "0000") {
                        this.templateForm = res.data;
                    }
                });
            },
            //加载模板原子列表
            refresh() {
                this.$refs['tamplateAtomTable'].reloadData();
            },
            remoteTableDatas(queryData) {
                queryData["productTemplateId"] = this.templateForm.id;
                // console.info("queryData:"+JSON.stringify(queryData));
                getProductTemplateDetails(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.tamplateAtomTable.updateTableData(records, total);
                    }
                });
            },
            //数据字典
            initDatadic() {
                getDictDataByType("templateCategory").then(res => {
                    if (res.code === "0000") {
                        this.templateCategoryQuery = res.data;
                    }
                });
            },
            //退回
            backPage() {
                this.$emit('next', "退回")
            },
            //保存模板信息
            save() {
                this.$refs.templateForm.validate((valid) => {
                    if (valid) {
                        this.submitLoading = true;
                        saveOrUpdateTemplate(this.templateForm).then(res => {
                            this.submitLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.templateForm = res.data;
                                console.info("保存完毕的信息"+JSON.stringify(res.data))
                                this.templateParms.id = this.templateForm.id;
                                this.numberReadonly = true;
                                this.refresh();
                            }
                        }).catch(() => {
                            this.submitLoading = false;
                        });
                    } else {
                        this.$Message.error('数据不完整!');
                    }
                })
            },
            //保存模板原子信息
            saveTemplateAtom() {
                if (this.selectAtomCount <= 0) {
                    this.$Message.warning("您还未选择数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认保存吗",
                    content: "您确认要保存所选的 " + this.selectAtomCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectAtomList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.submitLoading = true;
                        saveTemplateAtom({ids: ids, productTemplateId: this.templateParms.id}).then(res => {
                            this.submitLoading = false;
                            if (res.code === "0000") {
                                this.templateForm = res.data;
                                this.templateParms.id = this.templateForm.id;
                                this.numberReadonly = true;
                                this.refresh();
                                this.isShowModel = false;
                            }
                        }).catch(() => {
                            this.submitLoading = false;
                        });
                    }
                });
            },
            //打开弹窗，新增模板原子
            add() {
                if (this.templateForm.id == "" || this.templateForm.id == null) {
                    this.$Message.warning("请先保存模板！");
                } else {
                    this.isShowModel = true;
                    this.$refs['atomTable'].reloadData();
                }
            },
            //原子信息初始化
            queryData(queryData) {

                // getProductList(queryData).then(res => {
                //     if (res.code === "0000") {
                //         let {records, total} = res.data;
                //         this.$refs.atomTable.updateTableData(records, total);
                //     }
                // });
                queryData["condition"]["productTemplateId"] = this.templateForm.id;
                queryData["condition"]["templateCategory"] = this.templateForm.templateCategory;

                console.log("查询原子信息"+JSON.stringify(queryData));
                getProducttemplateAtomList(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.atomTable.updateTableData(records, total);
                    }
                });
            },
            clearAtomSelectAll() {
                this.$refs.atomTable.getTable().selectAll(false);
            },
            changeAtomSelect(e) {
                this.selectAtomList = e;
                this.selectAtomCount = e.length;
            },
            //模板原子选择
            changeSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            isMust() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要设置必填的数据");
                    return;
                }
                try {
                    this.selectList.forEach(e => {
                        if ("1" === e.atomIsDefault) {
                            throw new Error("");
                        }
                    });
                } catch (e) {
                    this.$Message.warning("您选择数据有默认原子,不编辑");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认设置必填吗",
                    content: "您确认要设置必填所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach((e) => {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.operationLoading = true;
                        isMust({ids: ids}).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("设置成功");
                                this.refresh();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },
            isNotMust() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要设置不必填的数据");
                    return;
                }
                try {
                    this.selectList.forEach(e => {
                        if ("1" === e.atomIsDefault) {
                            throw new Error("");
                        }
                    });
                } catch (e) {
                    this.$Message.warning("您选择数据有默认原子,不编辑");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认设置不必填吗",
                    content: "您确认要设置不可编辑所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.operationLoading = true;
                        isNotMust({ids: ids}).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("设置成功");
                                this.refresh();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },
            removeAll() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要删除的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认删除吗",
                    content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.operationLoading = true;
                        removeAll({ids: ids, id: this.templateParms.id}).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("删除成功");
                                this.templateForm = res.data;
                                this.templateParms.id = this.templateForm.id;
                                this.numberReadonly = true;
                                this.refresh();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },
            moveTemplateAll(moveType) {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要移动的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认移动吗",
                    content: "您确认要移动所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.operationLoading = true;
                        moveTemplateAll({
                            ids: ids,
                            id: this.templateParms.id,
                            moveType: moveType
                        }).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("移动成功");
                                this.templateForm = res.data;
                                this.templateParms.id = this.templateForm.id;
                                this.numberReadonly = true;
                                this.refresh();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },
        },
        created() {
        },
        computed: {
            defines() {
                return [
                    {
                        id: "defineProductAtom",
                        fields: productAtomDefine
                    }
                ];
            }
        },
        mounted() {
            this.getProductTemplateInfoDetail(this.templateParms);
            this.initDatadic();
        }
    };
</script>
<style scoped>
    .common_br {
        background-color: #f7f7f7;
        border-radius: 3px;
        border: 1px solid #dcdee2;
    }

    .common_title {
        font-size: 12px;
        padding-left: 48px;
        background: #f7f7f7;
        line-height: 38px;
        border-bottom: 1px solid #dcdee2;
        font-weight: normal;
    }

    .common_content {
        background-color: white;
        padding: 16px;
    }
</style>
